import {
  getVideoInfo,
  getFreeVideoInfo,
  getCourseMkInfo,
  getFreeCourseMkInfo,
  getVideoProgress,
  getCollectSection
} from '@/api/play'
import { Message } from 'element-ui'
export default {
  namespaced: true,
  state: {
    // 显示评分弹窗
    showGradeDialog: false,
    // 显示选择班级弹窗
    showChooseClassDialog: false,
    // 商品列表
    recommends: {},
    // 权限集信息
    coursePackInfo: {},
    // 单权限课程信息
    courseInfo: {},
    // 课程目录信息
    courseMkInfo: {},
    // 判断是权限集还是权限
    isPackCourse: false,
    // 当前选中的状态
    selectInfo: {
      year: '', //年份
      classIndex: '', //班级
      course_id: '', //课程id
      course_name: '', //课程名称
      class_name: '', //班级名称
      teacher_id: '',
      teacher: {}, //老师信息
      teachers: [], //老师列表
      years: [], //年份列表
      course_section_id: '', //当前课节id
      course_section_name: ''
    },
    // 年份老师对照关系
    yearTeacherMap: {},
    // 课节详情保留，线路切换使用
    sectionDetal: {},
    // 当前正在播放的课节
    playingSection: {},
    // 选中的商品(科目筛选)
    currentProducts: {},
    // 是否实操权限集
    isScCourse: false,
    // 笔记列表
    noteList: [],
    // 当前课程所有视频进度
    courseVideoProgress: [],
    // 当前正在播放的视频进度
    currentVideoProgress: {},
    // 当前课程最近一次观看视频的id
    courseLastVid: null,
    // 视频长度
    videoDuration: 0,
    // 当前显示讲义秒数
    currentSecond: 0,
    //当前播放内容所对应的知识点
    currentSite: {},
    // 当前视频播放时间
    currentTime: '0',
    // 课节收藏Map
    sectionCollectMap: {},
    // 专业科目信息
    professionSubjectInfo: {},
    // 展示课程的状态 0 ：展示课程，1：展示直播，2：展示没有课程
    videoImgType: 0,
    softInfo: {},
    // 展示视频状态，
    isShowVideoStatus: '',
    // 保存多线路
    videoLineArr: [],
    // 当前选中线路
    currentLineIndex: 0
  },
  mutations: {
    SET_POINT(state, data) {
      state.playingSection.points = data
    },
    TOGGLE_GRADE_DIALOG(state, data) {
      state.showGradeDialog = data
    },
    TOGGLE_CHOOSE_CLASS_DIALOG(state, data) {
      state.showChooseClassDialog = data
    },
    SET_COURSE_PACKINFO(state, data) {
      state.coursePackInfo = data
    },
    SET_COURSE_INFO(state, data) {
      state.courseInfo = data
    },
    SET_PLAYING_SECTION(state, data) {
      if (Array.isArray(data.points)) {
        data.points = data.points.map(item => {
          if (typeof item.isShow !== 'boolean') {
            item.isShow = false
          }
          return item
        })
      }
      state.playingSection = data
    },
    SET_SECTION_DETAIL(state, data) {
      state.sectionDetal = data
    },
    SET_SELECT_INFO(state, data) {
      state.selectInfo = data
    },
    setProfessionId(state, val) {
      // 只用两个参数 一个时state ,另一个是可以 字符串、对象、数组等
      state.professionId = val
    },
    setRecommend(state, data) {
      state.recommends = data
    },
    setIsPackCourse(state, data) {
      state.isPackCourse = data
    },
    setCourseMkInfo(state, data) {
      state.courseMkInfo = data
    },
    // 设置年份老师对照关系
    setYearTeacherMap(state, val) {
      let { teachers, dir_class = [] } = val

      state.yearTeacherMap = dir_class.reduce((obj, item) => {
        // 为年份赋初值
        let teacher = teachers.filter(
          tea => tea.teacher_id === item.teacher_id
        )[0]
        if (obj[item.year]) {
          //存在此年份属性
          obj[item.year].push(teacher)
        } else {
          obj[item.year] = []
          obj[item.year].push(teacher)
        }
        return obj
      }, {})
    },
    // 设置是否实操权限集
    setIsScCourse(state, val) {
      state.isScCourse = val
    },
    // 设置笔记列表数据[Hu Bin]
    SET_NOTE_LIST(state, data) {
      state.noteList = data
    },
    // 设置当前播放视频进度
    setVideoProgress(state, data) {
      state.currentVideoProgress = data
    },
    // 设置当前课程最近一次观看的视频id
    setCourseLastVid(state, data) {
      state.courseLastVid = data
    },
    // 设置当前课程所有视频播放进度
    setCourseVideoProgress(state, data) {
      state.courseVideoProgress = data
    },
    // 设置视频长度（author: Hu Bin）
    SET_VIDEO_DURATION(state, data) {
      state.videoDuration = data
    },
    // 设置当前讲义秒数（author: Hu Bin）
    SET_CURRENT_SECOND(state, data) {
      state.currentSecond = data
    },
    // 设置当前播放的知识点
    SET_CURRENT_SITE(state, data) {
      state.currentSite = data
    },
    setCurrentTime(state, data) {
      state.currentTime = data
    },
    // 更新课节收藏Map
    SET_COLLECTION_MAP(state, data) {
      state.sectionCollectMap = data
    },
    // 设置专业科目信息
    SET_PROFESSION_SUBJECT_INFO(state, data) {
      state.professionSubjectInfo = data
    },
    // 设置是否显示直播图片
    setVideoImgType(state, data) {
      state.videoImgType = data
    },
    setSoftInfo(state, data) {
      state.softInfo = data
    },
    setShowVideoStatus(state, data) {
      state.isShowVideoStatus = data
    },
    SET_VIDEO_LINE_ARR(state, data) {
      state.videoLineArr = data
    },
    SET_CURRENT_LINE_INDEX(state, data) {
      state.currentLineIndex = data
    },
    // 每次上报进度后，更新本地进度信息
    UPDATE_LOCAL_VIDEO_PROGRESS(state, data) {
      let { courseVideoProgress } = state
      let { video_id, time } = data
      let reg = /^[0-9.]+$/
      let regNum = /^\d+$/
      time = reg.test(time) ? +time : 0
      Array.isArray(courseVideoProgress) &&
        courseVideoProgress.forEach(item => {
          if (item && +item.vid === +video_id) {
            item.s = +time
          }
        })
      // 若video_id不在数组中，并且video_id合法，则向数组添加该数据。
      if (regNum.test(video_id) && Array.isArray(courseVideoProgress)) {
        let isInArr = courseVideoProgress.some(item => +item.vid === +video_id)
        if (!isInArr) {
          courseVideoProgress.push({
            s: +time,
            vid: +video_id
          })
        }
      }
    }
  },
  actions: {
    toggleGradeDialog({ commit }, val) {
      commit('TOGGLE_GRADE_DIALOG', val)
    },
    toggleChooseClassDialog({ commit }, val) {
      commit('TOGGLE_CHOOSE_CLASS_DIALOG', val)
    },
    getCoursePackInfo({ commit }, val) {
      commit('SET_COURSE_PACKINFO', val)
    },
    getCourseInfo({ commit }, val) {
      commit('SET_COURSE_INFO', val)
    },
    // 设置当前正在播放的课节
    async getPlayingSection({ commit }, params) {
      commit('SET_PLAYING_SECTION', {})
      let { course_id } = params
      // 请求课节收藏Map
      let getParams = {
        from: 'web',
        course_id
      }
      getCollectSection(getParams)
        .then(res => {
          let {
            data: { sections },
            errcode
          } = res
          if (+errcode === 0) {
            if (sections) {
              commit('SET_COLLECTION_MAP', sections)
            }
          }
        })
        .catch(e => {})
      // 区分免费看课页面调用方法
      let isFreeCourse = location.href.includes('free_course_play.html')
      let callMethod = isFreeCourse ? getFreeVideoInfo : getVideoInfo
      let { data, errcode, errmsg } = await callMethod(params).catch(err => {
        return { errcode: 404, errmsg: '网络错误,请重试!' }
      })

      if (errcode !== 0) {
        commit('SET_PLAYING_SECTION', {})
        Message({ type: 'error', message: errmsg })
        return
      }
      // 广告按播放时间duration排序
      if (
        Array.isArray(data.section_adverts) &&
        data.section_adverts.length > 0
      ) {
        data.section_adverts.sort((a, b) => a.duration - b.duration)
      }
      commit('SET_SECTION_DETAIL', data)
      commit('SET_PLAYING_SECTION', data)
    },
    // 设置当前选择的状态
    setSelectInfo({ commit }, val) {
      commit('SET_SELECT_INFO', val)
    },
    // 获取课程目录信息
    async getCourseMkInfo({ commit }, params) {
      // isFreePlay 是否为免费看课页面
      let isFreePlay = location.href.includes('free_course_play.html')
      let callMethod = isFreePlay ? getFreeCourseMkInfo : getCourseMkInfo
      let { errcode, errmsg, data } = await callMethod(params).catch(err => {
        return { errcode: 404, errmsg: '网络错误，请重试！', data: {} }
      })

      if (errcode !== 0) {
        Message({ type: 'error', message: errmsg })
        return
      }
      commit('setCourseMkInfo', data)
    },
    // 设置笔记列表数据
    setNoteList({ commit }, val) {
      commit('SET_NOTE_LIST', val)
    },
    // 获取当前课程的所有视频进度
    async getVideoProgress({ commit, state, rootState }, params) {
      if (!rootState.user.isLogin) {
        return commit('setVideoProgress', {
          s: 0,
          vid: state.playingSection.video_id
        })
      }
      let last_vid = null
      let res = await getVideoProgress(params).catch(err => {
        return { errcode: 404, errmsg: '网络错误，请重试', data: {} }
      })
      let { errcode, errmsg, data } = res
      if (errcode !== 0) {
        Message({ type: 'error', message: errmsg })
      }
      if (data && data.videos) {
        commit('setCourseVideoProgress', data.videos)
        last_vid = data.last_vid
      }
      commit('setCourseLastVid', last_vid)
    },
    // 设置当前视频进度
    setCurVideoProgress({ commit, state }, params) {
      let video_id = params.video_id
      let videoProgress = {}
      let arr = state.courseVideoProgress
      if (arr.length) {
        videoProgress = arr.filter(item => +item.vid === +video_id)
        videoProgress = videoProgress.length
          ? videoProgress[0]
          : { s: 0, vid: video_id }
      } else {
        videoProgress = { s: 0, vid: video_id }
      }
      commit('setVideoProgress', videoProgress)
    },
    // 保存线路
    setVideoLineArr({ commit }, val) {
      commit('SET_VIDEO_LINE_ARR', val)
    },
    // 切换当前选中index
    setCurrentLineIndex({ commit }, val) {
      commit('SET_CURRENT_LINE_INDEX', val)
    }
  },
  getters: {}
}
